layui.use(['jquery','layer','table','form','laydate'],function() {
    var $ = layui.jquery;
    var layer = layui.layer;
    var table = layui.table;
    var form = layui.form;
    var laydate = layui.laydate;

    //现在时间
    var createDate = "";
    //绑定事件
    laydate.render({
        elem: '#createDate',
        type: 'datetime',
        trigger: 'click'
    })

    //刷新
    refresh = function refresh(){
        location.reload();
    }
    //返回
    $('#goBack').click(function () {
        parent.tabParentChange(3);
    })
    $(document).click(function () {
        parent.$('.rightMenu').hide();
    });

    //模糊查询
    search = function search(){
        var account = $("#account").val();
        var nickname = $("#nickname").val();
        var createDate = $("#createDate").val()
        getTable(account,nickname,createDate);
    }

    //高级检索
    retrieval = function retrieval(){
        layer.open({
            type : 2,
            title : "高级检索",
            area : [ '900px', '580px' ],
            shade : 0,
            offset: 'auto',
            content :"advanced-retrieval.html",
            btn:['确定','取消'],
            yes: function(index, layero){
                var child = layero.find('iframe').contents();
                var userCode = child.find("#userCode").val();
                var nickname = child.find("#nickname").val();
                var studyDate = child.find("#studyDate").val();
                var status = child.find("#status option:selected").val();
                var account = child.find("#account").val();
                var createDate = child.find("#createDate").val();
                var param = {
                    'consumption':0,
                    'userCode':userCode,
                    'nickname':nickname,
                    'studyDate':studyDate,
                    'status':status,
                    'account':account,
                    'createDate':createDate,
                }
                $.ajax({
                    url:"/user/notConsumptionBeforeUserAdvancedRetrieval",
                    data:param,
                    type:"post",
                    dataType:"json",
                    success:function (data) {
                        demoTable(data.data);
                        layer.close(layer.index);
                    }
                })
            }
        })
    }

    getTable("","","");
    //数据表格
    function getTable(account,nickname,createDate) {
        var data ={
            "account":account ,
            "nickname":nickname,
            "createDate":createDate,
            "consumption": 0
        }
        $.ajax({
            url:"/user/getNotConsumptionBeforeUser",
            data: data,
            type:"post",
            dataType:"json",
            success:function (data) {
                demoTable(data.data);
            }
        })
    }

    //表格
    function demoTable(data){
        table.render({
            elem:'#demoTable',
            title:"委托书",
            data:data,
            toolbar:'#button_ids',
            limit:10,
            page:{
                layout:['count','prev','page','next','limit','skip','refresh'],
                limits:[10,20,30],
                first:"首页",
                last:"尾页",
            },
            cols:[[
                {type:'checkbox'},
                {title: '序号',align:'center', templet: function (data) {
                        return data.LAY_INDEX;
                    }},
                {field:"userCode",title:"用户编号",align:'center'},
                {field:"account",title:"用户账号",align:'center'},
                {field:"nickname",title:"用户昵称",align:'center'},
                {field:"studyDate",title:"学习时长",align:'center',templet:function(data){
                        return data.studyDate+'分钟';
                    }},
                {field:"consumption",title:"用户消费总金额",align:'center',templet:function(data){
                        return data.consumption+'￥';
                    }},
                {field:"createDate",title:"账号注册时间",align:'center'},
                {field:"status",title:"状态",align:'center',templet:function(data){
                        if(data.status==2){
                            return "正常";
                        }else if(data.status==3){
                            return "禁言";
                        }else if (data.status == 4) {
                            return "注销";
                        }else if (data.status == 5) {
                            return "封停";
                        }else{
                            return "无状态";
                        }
                    }},
                {field:'',title:"操作",align:'center',toolbar:'#button_caozuo'}
            ]]
        })
    }

    //查看编辑封停
    table.on('tool(demoTable)',function (obj) {
        var event = obj.event;
        if(event == "selectUser"){
            getTime();
            layer.open({
                type:2,
                title:"查看",
                area:["95%","100%"],
                scrollbar: false,
                offset:'auto',
                btn:["确定","取消"],
                content:"/user/userManage/userList/user-list-select.html",
                success:function(layero,index){
                    var child = layero.find('iframe').contents();
                    child.find("#userCode").text(obj.data.userCode);
                    child.find("#account").text(obj.data.account);
                    child.find("#nickname").text(obj.data.nickname);
                    child.find("#studyDate").text(obj.data.studyDate);
                    child.find("#consumption").text(obj.data.consumption);
                    child.find("#intention").text(obj.data.intention);
                    child.find("#freestyle").text(obj.data.freestyle);
                    child.find("#idCard").text(obj.data.idCard);
                    child.find("#remarks").text(obj.data.remarks);
                    child.find("#email").text(obj.data.email);
                    child.find("#avatarUrl").attr("src",obj.data.avatarUrl);
                },
                end:function (layero, index) {
                    layer.close(index);
                }
            });
        }else if(event == "updateUser"){
            localStorage.setItem("UserStatus",obj.data.status);
            layer.open({
                type:2,
                title:"编辑",
                area:["800px","500px"],
                offset: 'auto',
                btn:["确定","取消"],
                content:"/user/userManage/userList/user-list-update.html",
                success:function(layero,index){
                    var childUpdate = layero.find('iframe').contents();
                    childUpdate.find("input[name=userCode]").val(obj.data.userCode);
                    childUpdate.find("input[name=nickname]").val(obj.data.nickname);
                    childUpdate.find("input[name=consumption]").val(obj.data.consumption);
                    childUpdate.find("#remarks").val(obj.data.remarks);
                    childUpdate.find("#freestyle").val(obj.data.freestyle);
                },
                yes:function( index,layero){
                    var childUpdate = layero.find('iframe').contents();
                    var param = {
                        'userId': obj.data.userId,
                        'nickname':childUpdate.find("input[name=nickname]").val(),
                        'consumption':childUpdate.find("input[name=consumption]").val(),
                        'remarks':childUpdate.find("#remarks").val(),
                        'freestyle':childUpdate.find("#freestyle").val(),
                        'status': childUpdate.find("#status").val(),
                    }
                    $.ajax({
                        url:"/user/editBeforeUserByUserId",
                        data:param,
                        type:'post',
                        dataType:'json',
                        success:function (data) {
                        }
                    })
                    layer.close(index);
                },
                btn2:function(index,layero){
                    layer.close(index);
                },
                end:function () {
                    getTable("","","");
                }
            });
        }else if (event == "shutdownUser") {
            var child;
            getTime();
            if(obj.data.status == 5) {
                layer.msg("此账号已被封停");
            }else{
                layer.open({
                    type:2,
                    title:"封停用户",
                    area:["700px","500px"],
                    offset: 'auto',
                    btn:["确定","取消"],
                    content:"/user/userManage/userList/shut-down-user.html",
                    success:function(layero,index){
                        child = layero.find('iframe').contents();
                        child.find("input[name=account]").val(obj.data.account);
                    },
                    yes:function(index,layero){
                        $.ajax({//封停
                            url:"/user/editBeforeUserStatus",
                            data:{'status':5,'userId':obj.data.userId},
                            type:'post',
                            dataType:'json',
                            success:function (data) {
                                var param={
                                    'userId': obj.data.userId,
                                    'type':2,
                                    'reason':child.find("#reason").val(),
                                    'startDate': createDate,
                                    'endDate': getTimes(child.find('#day').val()),
                                    'days': child.find('#day').val(),
                                }
                                $.ajax({//添加封停记录日志
                                    url:"/user/addclosure",
                                    data:param,
                                    type:'post',
                                    dataType:'json',
                                    success:function (data) {
                                        getTable("","","");
                                        layer.msg("已封停");
                                        layer.close(index)
                                    }
                                })
                            }
                        })
                    },
                    end:function (layero, index) {
                        layer.close(index);
                    }
                });
            }
        }
    })

    //赠送优惠卷
    var arr = [];
    table.on('checkbox(demoTable)',function(obj){
        if(obj.type=='one'){
            if(obj.checked){//被选中为true
                arr.push(obj.data.userId)
            }else{//取消 false
                for (var i=0 ; i<arr.length ; i++){
                    if(arr[i] == obj.data.userId){
                        var local = $.inArray(arr[i],arr);//获取元素
                        arr.splice(local,1);//截取元素
                    }
                }
            }
        }else if(obj.type=='all'){
            arr = [];
            if(obj.checked){
                var checkStatus = table.checkStatus('demoTable');//获取表格全部的DOM数据
                $(checkStatus.data).each(function (i, o) {//i 下标从零开始 odata数据
                    arr.push(o.userId);
                });
            }else {
                arr = [];
            }
        }
    })

    addCoupon = function addCoupon(){
        if(arr.length==0){
            layer.msg("请选择一个用户进行赠送！！");
        }else{
            layer.open({
                type:2,
                title:"赠送优惠券",
                area:["1000px","600px"],
                offset: 'auto',
                btn:['确定','取消'],
                content:"/user/userManage/userList/complimentary-coupon.html",
                success:function(layero,index){
                },
                yes:function (layero, index) {
                    var  couponId = localStorage.getItem("couponId");
                    getTime();
                    $.ajax({//查询发行量和使用量
                        url:'/user/getUserCouponById',
                        data:{'couponId':couponId},
                        type:'post',
                        dataType:'json',
                        success:function (data) {//判断结束时间，和开始时间
                            if(createDate < data.data.endDate){
                                if(createDate > data.data.endDate){
                                    if(data.data.issueQuantity - data.data.used>=arr.length){
                                        for(var i=0; i<arr.length; i++){//添加使用记录 送多个用户
                                            var param = {
                                                "couponId": couponId,
                                                "userId": arr[i],
                                                "getDate": createDate,
                                                "usedState": 2
                                            };
                                            $.ajax({
                                                url:'/user/addUserCouponUsed',
                                                data:param,
                                                type:'post',
                                                dataType:'json',
                                                success:function (data) {
                                                }
                                            });
                                        }
                                        var circulation = data.data.used;
                                        var used = circulation + arr.length;
                                        $.ajax({//修改发行量
                                            url:'/user/editUserCouponByUsed',
                                            data:{'used' : used,'couponId' : couponId},
                                            type:'post',
                                            dataType:'json',
                                            success:function (data) {
                                                layer.msg('赠送成功！！！');
                                            }
                                        });
                                    }else{
                                        layer.msg("当前优惠券剩余数量不足 无法赠送！！！")
                                    }
                                }else{
                                    layer.msg("优惠卷没有到开放时间，无法赠送！！！")
                                }
                            }else{
                                layer.msg("优惠卷已过期！！！")
                            }
                        }
                    });
                    layer.close(layer.index);
                },
                end:function (layero, index) {
                    layer.close(index);
                }
            })
        }
    }

    //现在时间
    function getTime(){
        var date=new Date();
        var year=date.getFullYear();
        var month=date.getMonth()+1;
        var day=date.getDate();
        var hour=date.getHours();
        var minute=date.getMinutes();
        var second=date.getSeconds();
        var dateStr = year+"-"+zeroFilling(month)+"-"+zeroFilling(day)+" "+zeroFilling(hour)+":"+zeroFilling(minute)+":"+zeroFilling(second);
        createDate = dateStr;
    }

    //封停后的时间 天数加数字转化格式
    function getTimes(days){
        var oldDate=new Date();
        var date = new Date(oldDate.setDate(oldDate.getDate()+parseInt(days)));
        var year=date.getFullYear();
        var month=date.getMonth()+1;
        var day=date.getDate();
        var hour=date.getHours();
        var minute=date.getMinutes();
        var second=date.getSeconds();
        var dateStr = year+"-"+zeroFilling(month)+"-"+zeroFilling(day)+" "+zeroFilling(hour)+":"+zeroFilling(minute)+":"+zeroFilling(second);
        return dateStr;
    }

    function zeroFilling(data){
        if(data<10){
            data="0"+data;
        }
        return data;
    }

})